package sguigu.threee.controller;

import org.redisson.Redisson;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2022/12/16 16:16
 * @Version: 1.0
 */
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/redissonLock")
    @ResponseBody
    public void redissonLock(){

        RLock redissonLock = redissonClient.getLock("REDIS_LOCK");
        redissonLock.lock();
        try{
    	    //业务逻辑
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }finally{
            redissonLock.unlock();
        }

    }


    /**
     * 使用 getSemaphore 模拟停车位
     * @return
     * @throws InterruptedException
     */

    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
//        park.acquire();
        boolean b = park.tryAcquire();
        if (b){
            return "停进";
        }else{
            return "无位置";
        }
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();
        return "开走";
    }

    /**
     *  门栓（CountDownLatch）
     * @return
     */

    @GetMapping("/setLatch")
    @ResponseBody
    public String setLatch() {
        RCountDownLatch latch = redissonClient.getCountDownLatch("CountDownLatch");
        try {
            latch.trySetCount(5);
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "门栓被放开";

    }

    @GetMapping("/offLatch") //Classic Quorum Stream
    @ResponseBody
    public String offLatch() {
        RCountDownLatch countDownLatch = redissonClient.getCountDownLatch("CountDownLatch");
        countDownLatch.countDown();
        return "门栓被放开1";
    }

}
